import { useMemoizedFn, useSafeState } from "ahooks";
import { XHSUser } from "@common/models";
import { getValueOrDie } from "@common/utils";
import { useContext, useEffect, useRef } from "react";
import { GlobalModel } from "@/ui/context";
import { XHSComment } from "@common/models/xhs/notes";
import type { Poster } from "@/ui/cpts/biz/XHSTalks/meta";

export const useViewModel = () => {
  const globalModels = getValueOrDie(useContext(GlobalModel));
  const [commentToReply, setCommentToReply] = useSafeState<
    XHSComment | undefined
  >();
  const [sender, setSender] = useSafeState<XHSUser>(
    getValueOrDie(globalModels.sessions[0].apps.xhs.user),
  );

  const [curTabKey, setCurTabKey] = useSafeState<string>("mention");

  const mentionRef = useRef<{
    post: Poster;
  }>(null);
  const commentRef = useRef<{
    post: Poster;
  }>(null);
  const onTabSwitch = useMemoizedFn((key) => {
    setCurTabKey(key);
    setCommentToReply(undefined);
  });

  const { note } = getValueOrDie(globalModels?.discussion);

  useEffect(() => {
    setCurTabKey("mention");
  }, [note]);

  return {
    curTabKey,
    mentionRef,
    commentRef,
    sender,
    globalModels,
    commentToReply,
    note,

    setSender,
    setCommentToReply,
    onTabSwitch,
  };
};
